﻿using AutoMapper;
using Comain;
using Comain.DTO;
using Common;
using IRepository;
using IService;
using IService.Rempos;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    /// <summary>
    /// 实现类
    /// </summary>
    public class GoodsService : IGoodsService
    {
        private readonly IBaseRepository<Goods> dal;

        private readonly ILogger<GoodsService> logger;

        private readonly IBaseRepository<T_GoodsType> goffd;

        private readonly IBaseRepository<T_Goods> dd;

        private readonly IMapper mapper;

        public GoodsService(IBaseRepository<Goods> dal,ILogger<GoodsService> logger,IBaseRepository<T_GoodsType> goffd,IBaseRepository<T_Goods> dd,IMapper mapper)
        {
            this.dal = dal;
            this.logger = logger;
            this.goffd = goffd;
            this.dd = dd;
            this.mapper = mapper;
        }
        public async Task<bool> AddGood(T_Goods goodsd)
        {
            return await dd.AddAsync(goodsd);
        }
        /// <summary>
        /// 显示商品信息
        /// </summary>
        /// <returns></returns>
        public async Task<PageComm<List<GoodsDTO>>> Show(string? name, int? goodid, DateTime? time, int pageIndex, int pageSize)
        {
            //获取所有商品信息
            IQueryable<T_Goods> goodlist = dd.GetAllAsync();
            //判断
            if (!string.IsNullOrEmpty(name))                       
            {
                goodlist = goodlist.Where(x => x.Goods_Name.Contains(name));
            }
            if (goodid != null)
            {
                goodlist = goodlist.Where(x => x.GoodsId == goodid);
            }
            if (time != null)
            {
                goodlist = goodlist.Where(x => x.Goods_Create == Convert.ToDateTime(time).AddDays(1).Date);
            }
            //计算数据总数
            int tatalCount = goodlist.Count();
            //计算总页数
            int pageCount = (int)Math.Ceiling(tatalCount * 1.0 / pageSize);
            //完成分页效果 Skip:跳过 Take:取
            goodlist = goodlist.Skip((pageIndex - 1) * pageSize).Take(pageSize);


            //将商品信息类型转换成List<> 
            List<GoodsDTO> goodsDTOs = mapper.Map<List<GoodsDTO>>(goodlist);
            
            foreach (var item in goodsDTOs)
            {
                //商品品牌编号（item.GoodsId） 想获取：商品品牌名称
                item.GoodsName = (await dal.GetAll(item.GoodsId)).GoodsName;
                item.GoodsType_Name = await GetTypeName(item.GoodsType_Id);
            }

            return new PageComm<List<GoodsDTO>>()
            {
                Comm_MyProprty = goodsDTOs,
                Comm_PageCount = pageCount,
                Comm_TotalCount = tatalCount
            };
        }
        /// <summary>
        /// 获取商品分类的方法
        /// </summary>
        /// <param name="goodsTypeId"></param>
        /// <returns></returns>
        public async Task<string> GetTypeName(string goodsTypeId)
        {
            try
            {
                string typeName = "";
                //将字段用逗号分割Split(',')
                string[] gltds = goodsTypeId.Split(',');
                //遍历循环数组
                foreach (var item in gltds)
                {
                    //调用商品分类的反填方法
                    typeName += (await goffd.GetAll(Convert.ToInt32(item))).GoodsType_Name + ',';
                }
                return typeName.TrimEnd(',');
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取所有商品品牌信息
        /// </summary>
        /// <returns>返回满足条件的数据</returns>
        public IQueryable<Goods> ShowGoods()
        {
            try
            {
                return dal.GetAllAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("获取所有商品品牌信息异常" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 获取所有商品分类信息
        /// </summary>
        /// <param name="perentid">父级分类编号（作为条件进行筛选）</param>
        /// <returns>返回所有商品分类信息</returns>
        public List<Cascaderitrm> ShowGoodsTypes(int perentid)
        {
            //获取所有商品分类信息
            IQueryable<T_GoodsType> gdssd = goffd.GetAllAsync().Where(x => x.GoodsType_ParentId == perentid);
            //创建级联选择器标准格式集合
            List<Cascaderitrm> cascaderitrms = new List<Cascaderitrm>();
            
            //通过循环遍历所有商品分类型信息,将获取到的商品分类编号分类名称保存到级联选择器标准格式集合中
            foreach (var g in gdssd)
            {
                cascaderitrms.Add(new Cascaderitrm()
                {
                    value = g.GoodsType_Id,
                    label = g.GoodsType_Name,
                    children = ShowGoodsTypes(g.GoodsType_Id)
                }); 
            }
            return cascaderitrms;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DeleteAsync(int id)
        {
            T_Goods t_Goods = await dd.GetAll(id);
            t_Goods.IsDel = true;
            return await dd.UpdateAsyncs(t_Goods);
        }

        public Task<int> State(int id, int states)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T_Goods> GetT_Goods(int id)
        {
            return await dd.GetAll(id);
        }
        /// <summary>
        /// 修改商品
        /// </summary>
        /// <param name="goodsds"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> UpdateGood(T_Goods goodsds)
        {
            return await dd.UpdateAsync(goodsds);
        }
    }
}
